package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.TReport;
import com.ruoyi.system.domain.bo.SheetBo;
import com.ruoyi.system.domain.bo.TReportBo;
import com.ruoyi.system.mapper.TReportMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.TTemplateBo;
import com.ruoyi.system.domain.vo.TTemplateVo;
import com.ruoyi.system.domain.TTemplate;
import com.ruoyi.system.mapper.TTemplateMapper;
import com.ruoyi.system.service.ITTemplateService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 模板Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-06
 */
@RequiredArgsConstructor
@Service
public class TTemplateServiceImpl implements ITTemplateService {

    private static final String defaultJson = "[{\"name\":\"Sheet1\",\"color\":\"\",\"status\":\"1\",\"order\":\"0\",\"config\":{},\"index\":0,\"jfgird_select_save\":[],\"luckysheet_select_save\":[{\"row\":[0,0],\"column\":[0,0],\"row_focus\":0,\"column_focus\":0,\"left\":0,\"width\":73,\"top\":0,\"height\":19,\"left_move\":0,\"width_move\":73,\"top_move\":0,\"height_move\":19}],\"visibledatarow\":[20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500,520,540,560,580,600,620,640,660,680,700,720,740,760,780,800,820,840,860,880,900,920,940,960,980,1000,1020,1040,1060,1080,1100,1120,1140,1160,1180,1200,1220,1240,1260,1280,1300,1320,1340,1360,1380,1400,1420,1440,1460,1480,1500,1520,1540,1560,1580,1600,1620,1640,1660,1680],\"visibledatacolumn\":[74,148,222,296,370,444,518,592,666,740,814,888,962,1036,1110,1184,1258,1332,1406,1480,1554,1628,1702,1776,1850,1924,1998,2072,2146,2220,2294,2368,2442,2516,2590,2664,2738,2812,2886,2960,3034,3108,3182,3256,3330,3404,3478,3552,3626,3700,3774,3848,3922,3996,4070,4144,4218,4292,4366,4440],\"ch_width\":4560,\"rh_height\":1760,\"luckysheet_selection_range\":[],\"zoomRatio\":1,\"celldata\":[]},{\"name\":\"Sheet2\",\"color\":\"\",\"status\":\"0\",\"order\":\"1\",\"config\":{},\"index\":1,\"celldata\":[]},{\"name\":\"Sheet3\",\"color\":\"\",\"status\":\"0\",\"order\":\"2\",\"config\":{},\"index\":2,\"celldata\":[]}]";
    private final TTemplateMapper baseMapper;
    private final TReportMapper reportMapper;

    /**
     * 查询模板
     */
    @Override
    public TTemplateVo queryById(String pkid){
        TTemplateVo vo = new TTemplateVo();
        LambdaQueryWrapper<TTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TTemplate::getPkid,pkid);
        List<TTemplateVo> vos = baseMapper.selectVoList(wrapper);
        if (ObjectUtil.isNull(vos.get(0).getReportData())) {
            vo.setReportData(JSONUtil.parseArray(defaultJson));
        }else{
            vo.setReportData(JSONUtil.parseArray(vos.get(0).getReportData()));
        }
        return vo;
    }

    /**
     * 查询模板列表
     */
    @Override
    public TableDataInfo<TTemplateVo> queryPageList(TTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TTemplate> lqw = buildQueryWrapper(bo);
        Page<TTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询模板列表
     */
    @Override
    public List<TTemplateVo> queryList(TTemplateBo bo) {
        LambdaQueryWrapper<TTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TTemplate> buildQueryWrapper(TTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TTemplate> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getReportData()), TTemplate::getReportData, bo.getReportData());
        return lqw;
    }

    /**
     * 新增模板
     */
    @Override
    public Boolean insertByBo(TTemplateBo bo) {
        TTemplate add = BeanUtil.toBean(bo, TTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPkid(add.getPkid());
        }
        return flag;
    }

    /**
     * 修改模板
     */
    @Override
    public Boolean updateByBo(TTemplateBo bo) {
        TTemplate update = BeanUtil.toBean(bo, TTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TTemplate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除模板
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Integer sendToAll(TTemplateBo bo) {
        //查询根据模板id，分发模板填报任务
        TTemplateVo vo = baseMapper.selectVoById(bo.getPkid());
        TReport re = new TReport();
        re.setReportName(bo.getUserName());
//        re.setPlantId(bo.getPkid());
        re.setReportId(bo.getPkid());
        re.setAudit("0");
        re.setReportData(String.valueOf(vo.getReportData()));
        re.setReportTime(DateUtil.parse(DateUtil.now()));
        return reportMapper.insert(re);
    }

    @Override
    public int saveLuckySheet(SheetBo bo) {
        LambdaUpdateWrapper<TTemplate> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TTemplate::getReportData,bo.getData())
                .eq(TTemplate::getPkid,bo.getPkid());
        return baseMapper.update(wrapper);
    }
}

